<template>
    <div class="flex h-[calc(100vh-50px)] bg-gray-100">
        <!-- 编辑模式：显示编辑面板和预览面板 -->
        <template v-if="!showPreview">
        <EditorPanel
            :resume-data="resumeData"
            :saving="saving"
            :exporting="exporting"
            :show-preview="showPreview"
            @add-education="addEducation"
            @remove-education="removeEducation"
            @add-work="addWork"
            @remove-work="removeWork"
            @add-project="addProject"
            @remove-project="removeProject"
            @add-skill="addSkill"
            @remove-skill="removeSkill"
            @save="saveResume"
            @toggle-preview="togglePreview"
            @export-pdf="exportToPdf"
            @reorder-sections="handleReorderSections"
        />

            <PreviewPanel
                :resume-data="resumeData"
                :full-width="false"
                :exporting="exporting"
                :section-order="sectionOrder"
                @export-pdf="exportToPdf"
            />
        </template>

        <!-- 预览模式：只显示预览面板 -->
        <PreviewPanel
            v-else
            :resume-data="resumeData"
            :full-width="true"
            :exporting="exporting"
            :section-order="sectionOrder"
            @export-pdf="exportToPdf"
            @back-to-edit="togglePreview"
        />
    </div>
</template>

<script setup lang="ts">
import { resumeApi } from '~/utils/api'
import { useSimplePdfExport } from '~/composables/useSimplePdfExport'
import { useAdvancedPdfExport } from '~/composables/useAdvancedPdfExport'
import { usePdfOptimizedExport } from '~/composables/usePdfOptimizedExport'
import EditorPanel from '~/components/Resume/EditorPanel.vue'
import PreviewPanel from '~/components/Resume/PreviewPanel.vue'

const route = useRoute()
const id = route.params.id
const isEdit = computed(() => id && id !== 'new')
const showPreview = ref(false)
const saving = ref(false)
const exporting = ref(false)

// 模块顺序
const sectionOrder = ref([
    'basic-info',
    'education', 
    'work-experience',
    'projects',
    'skills',
    'self-evaluation'
])

// PDF导出功能
const { exportResumeToPdf } = useSimplePdfExport()
const { exportToPdfAdvanced, isAdvancedPdfSupported } = useAdvancedPdfExport()
const { exportToPdfOptimized } = usePdfOptimizedExport()

// 简历数据结构
const resumeData = ref({
    name: '',
    phone: '',
    email: '',
    hometown: '',
    currentResidence: '',
    jobIntention: '',
    education: [] as Array<{
        school: string
        major: string
        degree: string
        startDate: string
        endDate: string
    }>,
    workExperience: [] as Array<{
        company: string
        position: string
        startDate: string
        endDate: string
        description: string
    }>,
    projects: [] as Array<{
        name: string
        role: string
        duration: string
        description: string
    }>,
    skills: [] as Array<{
        description: string
    }>,
    selfEvaluation: ''
})

// 添加教育经历
const addEducation = () => {
    resumeData.value.education.push({
        school: '',
        major: '',
        degree: '',
        startDate: '',
        endDate: ''
    })
}

// 删除教育经历
const removeEducation = (index: number) => {
    resumeData.value.education.splice(index, 1)
}

// 添加工作经历
const addWork = () => {
    resumeData.value.workExperience.push({
        company: '',
        position: '',
        startDate: '',
        endDate: '',
        description: ''
    })
}

// 删除工作经历
const removeWork = (index: number) => {
    resumeData.value.workExperience.splice(index, 1)
}

// 添加项目经验
const addProject = () => {
    resumeData.value.projects.push({
        name: '',
        role: '',
        duration: '',
        description: ''
    })
}

// 删除项目经验
const removeProject = (index: number) => {
    resumeData.value.projects.splice(index, 1)
}

// 添加专业技能
const addSkill = () => {
    resumeData.value.skills.push({
        description: ''
    })
}

// 删除专业技能
const removeSkill = (index: number) => {
    resumeData.value.skills.splice(index, 1)
}

// 切换预览模式
const togglePreview = () => {
    showPreview.value = !showPreview.value
}

// 处理模块重新排序
const handleReorderSections = (newOrder: string[]) => {
    console.log('收到重新排序请求:', newOrder)
    console.log('当前sectionOrder:', sectionOrder.value)
    sectionOrder.value = newOrder
    console.log('更新后sectionOrder:', sectionOrder.value)
}

// 导出PDF功能
const exportToPdf = async () => {
    try {
        exporting.value = true

        // 检查是否有简历内容
        if (!resumeData.value.name && !resumeData.value.phone && !resumeData.value.email) {
            alert('请先填写简历基本信息')
            return
        }

        // 获取预览区域的元素
        const previewElement = document.querySelector('.max-w-4xl') as HTMLElement
        if (!previewElement) {
            throw new Error('找不到预览内容')
        }

        // 生成文件名，移除特殊字符
        const name = resumeData.value.name || '简历'
        const cleanName = name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '_')
        const date = new Date().toISOString().split('T')[0]
        const filename = `${cleanName}_${date}.pdf`

        // 优先使用优化的PDF导出，确保占满整个页面宽度
        try {
            await exportToPdfOptimized(previewElement, filename)
            console.log('PDF导出成功（优化模式）')
        } catch (optimizedError) {
            console.warn('优化PDF导出失败，尝试高级模式:', optimizedError)
            try {
                const isSupported = await isAdvancedPdfSupported()
                if (isSupported) {
                    await exportToPdfAdvanced(previewElement, filename)
                    console.log('PDF导出成功（高级模式）')
                } else {
                    throw new Error('高级PDF导出不支持')
                }
            } catch (advancedError) {
                console.warn('高级PDF导出失败，使用简单导出:', advancedError)
                await exportResumeToPdf(previewElement, filename)
                console.log('PDF导出成功（简单模式）')
            }
        }
    } catch (error) {
        console.error('PDF导出失败:', error)
        alert('PDF导出失败，请重试')
    } finally {
        exporting.value = false
    }
}

// 保存简历
const saveResume = async () => {
    try {
        saving.value = true
        const content = JSON.stringify(resumeData.value)
        const title = resumeData.value.name || '简历'

        if (isEdit.value) {
            await resumeApi.updateResumeApi(Number(id), { title, content })
        } else {
            await resumeApi.createResumeApi({ title, content })
        }

        // 显示成功消息
        console.log('简历保存成功')
    } catch (error) {
        console.error('保存简历失败:', error)
        alert('保存简历失败，请重试')
    } finally {
        saving.value = false
    }
}

// 加载简历数据
const loadResume = async () => {
    if (isEdit.value) {
        try {
            const response = await resumeApi.getResumeByIdApi(Number(id))

            console.log(response, '');

            if (response.success && response.data) {
                const content = JSON.parse(response.data.content)
                resumeData.value = { ...resumeData.value, ...content }
            }
        } catch (error) {
            console.error('加载简历失败:', error)
            alert('加载简历失败')
        }
    }
}

// 自动保存功能已移除

// 初始化
onMounted(async () => {
    await loadResume()
    // 使用 nextTick 确保在客户端渲染完成后再添加默认数据
    await nextTick()
    // 添加默认的教育经历和工作经历
    if (resumeData.value.education.length === 0) {
        addEducation()
    }
    if (resumeData.value.workExperience.length === 0) {
        addWork()
    }
})

// 组件卸载时的清理逻辑已移除
</script>
